package com.dongyun.loraweb.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dongyun.loraweb.json.Grid;
import com.dongyun.loraweb.json.Result;


public abstract class AbstractController {
	protected final static String downDirectory=System.getProperty("user.dir")+File.separator+"download";
	
	protected Result createResult(){
		return createResult(false, "", null);
	}
	protected Result createResult(boolean success,String msg,Object value){
		Result result = new Result();
		result.setSuccess(success);
		result.setMsg(msg);
		result.setObj(value);
		return result;
	}
	protected Result createResult(boolean success,Object value){
		return createResult(success, "", value);
	}
	protected Result createResult(boolean success,String msg){
		return createResult(success, msg, null);
	}
	protected Result createResult(String msg){
		return createResult(false, msg, null);
	}
	protected Result createResult(String msg,Object value){
		return createResult(false, msg, value);
	}
	protected Result createSuccessResult(String msg){
		return createResult(true, msg, null);
	}
	protected Result createSuccessResult(String msg,Object obj){
		return createResult(true, msg, obj);
	}
	@SuppressWarnings("rawtypes")
	protected Grid createGrid(Long total,List list) {
		Grid grid = new Grid();
		grid.setTotal(total);
		grid.setRows(list);
		return grid;
	}
	
	/**
	 * 下载文件
	 * @param res
	 * @param fileName
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void downFile(HttpServletRequest request,HttpServletResponse res, String fileName) throws IOException, FileNotFoundException {
		File file=new File(fileName);
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");  
        res.setHeader("Content-Disposition", "attachment;filename="+processFileName(request, file.getName()));
        res.setContentLengthLong(file.length());
        BufferedInputStream bis = null;
        ServletOutputStream os = res.getOutputStream();
        try {
			bis = new BufferedInputStream(new FileInputStream(file));
			byte[] b = new byte[1024];
			while (bis.read(b) != -1) {
				os.write(b);
				os.flush();
			} 
		} finally {
			bis.close();
			os.close();
		}
	}
	/** 
     *  处理导出生成的Excel文件名在火狐或ie下出现乱码的问题
     * @Title: processFileName 
     *  
     * @Description: ie,chrom,firfox下处理文件名显示乱码 
     */  
    public static String processFileName(HttpServletRequest request, String fileNames) {  
        String codedfilename = null;  
        try {  
            String agent = request.getHeader("USER-AGENT");  
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent  
                    && -1 != agent.indexOf("Trident")) {// ie  
  
                String name = java.net.URLEncoder.encode(fileNames, "UTF8");  
  
                codedfilename = name;  
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等  
  
  
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return codedfilename;  
    }  
	
	/**
	 * 文件上传
	 * @param multiReq
	 */
	public File uploadFile(MultipartHttpServletRequest multiReq) {
		// 获取上传文件的路径
		String uploadFilePath = multiReq.getFile("file").getOriginalFilename();
		System.out.println("uploadFlePath:" + uploadFilePath);
		// 截取上传文件的文件名
		String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
		System.out.println("multiReq.getFile()" + uploadFileName);
		// 截取上传文件的后缀
		String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
		System.out.println("uploadFileSuffix:" + uploadFileSuffix);
		FileOutputStream fos = null;
		ByteArrayInputStream fis = null;
		try {
			fis = (ByteArrayInputStream) multiReq.getFile("file").getInputStream();
			File file = new File("upload\\" + uploadFileName + "."+uploadFileSuffix);
			if(!file.exists()){
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = fis.read(temp);
			while (i != -1) {
				fos.write(temp, 0, temp.length);
				fos.flush();
				i = fis.read(temp);
			}
			return file;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
